package com.zyfdroid.bigdialerkit;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.zyfdroid.bigdialerkit.dao.MissingCall;
import com.zyfdroid.bigdialerkit.services.MissedCallsRemoteViewsService;

/**
 * Implementation of App Widget functionality.
 */
public class MissingCallsWdiget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        @SuppressLint("RemoteViewLayout") RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.missing_calls_wdiget);
        Intent intent = new Intent(context, MissedCallsRemoteViewsService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
        views.setRemoteAdapter(R.id.listMissingCalls, intent);
        Intent listClickingIntent = new Intent(context, MissedCallDetailActivity.class);
        listClickingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        views.setPendingIntentTemplate(R.id.listMissingCalls, PendingIntent.getActivity(context,1481,listClickingIntent,PendingIntent.FLAG_MUTABLE));
        int count = MissingCall.LoadData(context).size();
        views.setTextViewText(R.id.lblMissingCallCount, count > 0 ? (count+"个未接电话") : "没有未接电话");
        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Log.d("MissingCallWidget", "updateAppWidget: Received, update "+appWidgetIds.length+" widgets.");
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context,appWidgetManager,appWidgetId);
            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId,R.id.listMissingCalls);
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}